<template>
  <el-dialog draggable title="选择商品" :model-value="visible" @close="handleClose" destroy-on-close align-center width="1100px" :close-on-click-modal="false">
    <div class="search mb-4">
      <el-input v-model="form.sku" placeholder="SKU" prefix-icon="search" clearable class="w-[160px] mr-4" type="textarea" :autosize="{ minRows: 1, maxRows: 3 }" />
      <el-input v-model="form.custom_sku" placeholder="自定义SKU" prefix-icon="search" clearable class="w-[160px] mr-4" type="textarea" :autosize="{ minRows: 1, maxRows: 3 }" />
      <el-input v-model="form.sai_he_sku" placeholder="赛盒SKU" prefix-icon="search" clearable class="w-[160px] mr-4" type="textarea" :autosize="{ minRows: 1, maxRows: 3 }" />
      <el-input v-model="form.sku_cn_title" placeholder="产品中文名称" prefix-icon="search" clearable class="w-[160px] mr-4" />
      <el-button type="primary" @click="search">查询</el-button>
    </div>
    <vxe-table
      ref="tableRef"
      :height="500"
      :column-config="{ resizable: true }"
      :row-config="{ keyField: 'id', isHover: true }"
      :data="tableData"
      :checkbox-config="checkboxConfig"
      :radio-config="radioConfig"
      @cell-click="cellClick"
      :show-overflow="false"
    >
      <vxe-column v-if="multiple" type="checkbox" width="50"></vxe-column>
      <vxe-column v-else type="radio" width="50"></vxe-column>
      <vxe-column title="产品图片" field="product_main_img" width="80">
        <template #default="{ row }">
          <!-- <div> -->
          <el-image :src="row.attr_img" width="30" height="30" style="border: 0.5px solid #f0f0f0; border-radius: 4px">
          </el-image>

          <!-- <VImage :width="58" :height="58" :src="row.attr_img"></VImage> -->
          <!-- </div> -->
        </template>
      </vxe-column>
      <vxe-column title="spu" field="spu"> </vxe-column>
      <vxe-column title="SKU/自定义SKU" width="180">
        <template #default="{ row }">
          <div class="text-blue-500">
            <div>{{ row.sku }}</div>
            <div>{{ row.custom_sku }}</div>
          </div>
        </template>
      </vxe-column>
      <vxe-column title="产品名称" field="sku_cn_title">
        <template #default="{ row }">
          <VText :value="row?.sku_cn_title" :line="2" />
        </template>
      </vxe-column>
      <vxe-column title="商品状态" field="spu_status_text" width="80"> </vxe-column>
      <vxe-column title="规格" width="150">
        <template #default="{ row }">
          <div class="text-blue-500">
            <div>颜色:</div>
            <div>尺码:</div>
          </div>
        </template>
      </vxe-column>
      <vxe-column title="采购价" width="80">
        <template #default="{ row }">
          <div class="text-blue-500">
            <div>￥{{ row.purchase_price }}</div>
          </div>
        </template>
      </vxe-column>

      <template #toolbar_btns> </template>
      <template #form="{ form }">
        <el-input v-model.trim="form.sku" :prefix-icon="Search" class="w-40" placeholder="SKU名称" clearable></el-input>
        <el-input v-model.trim="form.sai_he_sku" :prefix-icon="Search" class="w-40" placeholder="系统SKU" clearable></el-input>
        <el-input v-model.trim="form.custom_sku" :prefix-icon="Search" class="w-40" placeholder="自定义SKU" clearable></el-input>
      </template>
    </vxe-table>

    <template #footer>
      <div style="display: flex; justify-content: space-between; align-items: center; margin-top: 10px">
        <div>
          <vxe-pager
            :border="false"
            perfect
            v-model:current-page="pager.currentPage"
            v-model:page-size="pager.pageSize"
            :total="pager.totalResult"
            :page-sizes="[10, 20, 100]"
            @page-change="pageChange"
            :layouts="['PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'Sizes', 'FullJump', 'Total']"
          >
          </vxe-pager>
        </div>
        <div>
          <el-button @click="handleClose">取 消</el-button>
          <el-button type="primary" :loading="loadings.submit" @click="submit">保 存 </el-button>
        </div>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="jsx" setup>
import api from "./api"
import { ElMessage } from "element-plus"
import { Search } from "@element-plus/icons-vue"
// import VImage from "@/components/Image/index.vue"

const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  multiple: {
    type: Boolean,
    default: false,
  },
  selectIds: {
    type: Array,
    default: () => [],
  },
})
const emit = defineEmits(["update:visible", "close", "uploadSku"])

const tableRef = ref()
let loadings = reactive({})

const pager = reactive({
  totalResult: 1,
  currentPage: 1,
  pageSize: 10,
})
const data = reactive({
  form: {
    sku: "",
    custom_sku: "",
    sku_cn_title: "",
    sai_he_sku: "",
  },
})
const tableData = ref([])

const { form } = toRefs(data)

const checkboxConfig = ref({
  reserve: true,
})

watch(
  () => props.selectIds,
  (list) => {
    checkboxConfig.value.checkRowKeys = list
  },
  { deep: true, immediate: true }
)

const radioConfig = reactive({
  reserve: true,
  checkMethod({ row }) {
    const { selectIds = [] } = props
    return !selectIds.includes(row.sku)
  },
})

onMounted(() => {
  // initData()
})
watch(
  () => props.visible,
  (val) => {
    if (val) {
      initData()
    } else {
      form.value = {}
      tableData.value = []
    }
  }
)

watch(
  () => props.selectIds,
  (val) => {
    if (val && val.length) {
      const { multiple } = props
      if (multiple) {
        checkboxConfig.checkRowKeys = val
      } else {
      }
    } else {
      const { multiple } = props
      if (multiple) {
        tableRef.value?.clearCheckboxRow()
        tableRef.value?.clearCheckboxReserve()
      } else {
        tableRef.value?.clearRadioRow()
        tableRef.value?.clearRadioReserve()
      }
    }
  },
  { immediate: true }
)

const initData = (data = {}) => {
  // sku custom_sku
  let formData = { ...form.value }
  for (const key in formData) {
    formData[key] = formData[key].trim()
  }
  // console.log(form.value.sku.split('\n').map(v=>v.trim()));
  formData.sku = formData.sku
    ?.split("\n")
    .map((v) => v.trim())
    .filter(Boolean)
  formData.custom_sku = formData.custom_sku
    ?.split("\n")
    .map((v) => v.trim())
    .filter(Boolean)
  formData.sai_he_sku = formData.sai_he_sku
    ?.split("\n")
    .map((v) => v.trim())
    .filter(Boolean)
  api.query({ ...data, ...formData }).then(({ total, data }) => {
    tableData.value = data
    pager.totalResult = total
    if (data.pageNumber) {
      pager.pageNum = data.pageNum
      pager.pageSize = data.pageSize
    }
  })
}

const pageChange = () => {
  initData({ pageNum: pager.currentPage, pageSize: pager.pageSize })
}

const search = () => {
  initData({ pageNum: 1, pageSize: pager.pageSize })
}

const handleClose = () => {
  emit("update:visible", false)
}
// 单选
const cellClick = ({ row, rowIndex }) => {
  if (!props.multiple) {
    tableRef.value?.setRadioRow(row)
  }
}
const getSelectRow = () => {
  return [...tableRef?.value?.getCheckboxReserveRecords(true), ...tableRef?.value?.getCheckboxRecords(true)]
}

const submit = () => {
  const { multiple, selectIds } = props
  if (multiple) {
    let _list = getSelectRow()
    _list = _list.filter((n) => !selectIds.includes(n.sku))
    if (!_list.length) {
      ElMessage.warning("请先选择SKU!")
      return
    }
    emit("uploadSku", _list)
    handleClose()
  } else {
    const _item = tableRef?.value?.getRadioReserveRecord() || tableRef?.value?.getRadioRecord()

    if (!_item) {
      ElMessage.warning("请先选择SKU!")
      return
    }
    emit("uploadSku", _item)
    handleClose()
  }
}

defineExpose({ open })
</script>
